﻿using Raffles.OA.Utility;
using Raffles.OA.Data;
using Mapster;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Raffles.OA.WebApp.Areas.Manage.Controllers
{
    public class MenuController : BaseController<Menu>
    { 
        /// <summary>
        /// 获取菜单列表树形表格
        /// </summary> 
        /// <returns></returns>
        public JsonResult GetTreeData()
        {
            try
            {
                var data = _dbContext.Queryable<Menu>()
                                     .Where(x => !x.DeletedMark && x.EnabledMark)
                                     .OrderBy(x => x.DisplayOrder).ToList();

                return Json(DataResult<List<Menu>>.Success(data, "加载成功"), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"菜单树加载错误,错误原因:{ex.Message}"), JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Form(int? id)
        {
            Menu menu = new Menu();
            List<BaseVo> menuTypes = new List<BaseVo>();
            menuTypes.Add(new BaseVo() { Id = (int)MenuTypeEnum.Directory, Name = MenuTypeEnum.Directory.GetDescription() });
            menuTypes.Add(new BaseVo() { Id = (int)MenuTypeEnum.Menu, Name = MenuTypeEnum.Menu.GetDescription() });
            menuTypes.Add(new BaseVo() { Id = (int)MenuTypeEnum.Button, Name = MenuTypeEnum.Button.GetDescription() });
            menuTypes.Add(new BaseVo() { Id = (int)MenuTypeEnum.NewPage, Name = MenuTypeEnum.NewPage.GetDescription() });
            if (id != null)
            {
                menu = _dbContext.Queryable<Menu>().InSingle(id);
                ViewBag.Type = new SelectList(menuTypes, "Id", "Name", menu.Type);
            }
            else
            {
                ViewBag.Type = new SelectList(menuTypes, "Id", "Name", 0);
            }
            return View(menu);
        }

        /// <summary>
        /// 菜单保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveForm(MenuDto menuDto)
        {
            try
            {
                //重置缓存
                OperatorModel operatorModel = OperatorProvider.Provider.GetCurrent();
                CacheHelper.RemoveCache($"{operatorModel.Account}_{operatorModel.Id}");
                if (menuDto.Id == null)
                {
                    Menu menu = new Menu();
                    menuDto.Adapt(menu);
                    switch (menuDto.Type)
                    {
                        case (int)MenuTypeEnum.Directory:
                        case (int)MenuTypeEnum.Menu:
                            menu.Authorize = string.Empty;
                            break; 
                        case (int)MenuTypeEnum.Button:
                            menu.Icon = menu.UrlAddress = string.Empty; 
                            break;
                    }
                    menu.ParentId = menuDto.TreeId;
                    menu.CreatedOn = DateTime.Now;
                    menu.CreatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    _dbContext.Insertable<Menu>(menu).ExecuteCommand();
                    return Json(DataResult.Success("菜单新增成功"));
                }
                else
                {
                    Menu menu = _dbContext.Queryable<Menu>().InSingle(menuDto.Id);
                    menuDto.Adapt(menu);
                    switch (menuDto.Type)
                    {
                        case (int)MenuTypeEnum.Directory:
                        case (int)MenuTypeEnum.Menu:
                            menu.Authorize = string.Empty;
                            break;
                        case (int)MenuTypeEnum.Button:
                            menu.Icon = menu.UrlAddress = string.Empty;
                            break;
                    }
                    menu.ParentId = menuDto.TreeId;
                    menu.UpdatedOn = DateTime.Now;
                    menu.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    _dbContext.Updateable<Menu>(menu).ExecuteCommand();
                    return Json(DataResult.Success("菜单编辑成功"));
                }
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"保存失败,失败原因:{ex.Message}"));
            }
        }

        /// <summary>
        /// 菜单删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteData(int id)
        {
            if (_dbContext.Queryable<Menu>().Any(x => x.ParentId == id))
            {
                return Json(DataResult.Error("该菜单存在子菜单,不允许删除"));
            }
            if (_dbContext.Queryable<RoleMenu>().Any(x => x.MenuId == id))
            {
                return Json(DataResult.Error("该菜单已分配角色,不允许删除"));
            }
            //重置缓存
            OperatorModel operatorModel = OperatorProvider.Provider.GetCurrent();
            CacheHelper.RemoveCache($"{operatorModel.Account}_{operatorModel.Id}");
            Menu menu = _dbContext.Queryable<Menu>().InSingle(id);
            menu.DeletedMark = true;
            menu.UpdatedOn = DateTime.Now;
            menu.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
            _dbContext.Updateable<Menu>(menu).ExecuteCommand();
            return Json(DataResult.Success("删除成功"));
        }

        /// <summary>
        /// 状态改变
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangeStatus(int id)
        {
            Menu menu = _dbContext.Queryable<Menu>().InSingle(id);
            var result = menu.EnabledMark;
            menu.EnabledMark = !menu.EnabledMark;
            menu.UpdatedOn = DateTime.Now;
            menu.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
            _dbContext.Updateable<Menu>(menu).ExecuteCommand(); 
            return result == true ? Json(DataResult.Success("禁用成功")) : Json(DataResult.Success("启用成功"));
        }

        /// <summary>
        /// 获取菜单树
        /// </summary> 
        /// <returns></returns>
        public JsonResult GetMenuTreeSelect()
        {
            List<TreeVo> treeDtos = new List<TreeVo>();
            try
            {
                treeDtos = _dbContext.Queryable<Menu>().Where(x => !x.DeletedMark &&x.EnabledMark)
                                       .OrderBy(x => x.DisplayOrder)
                                       .Select(x => new TreeVo { id = x.Id, pId = x.ParentId, name = x.Name })
                                       .ToList();

                return Json(DataResult<List<TreeVo>>.Success(treeDtos, "加载成功"), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"下拉树加载错误,错误原因:{ex.Message}"), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 图标选择
        /// </summary>
        /// <returns></returns>
        public ActionResult Icon()
        {
            return View();
        }
    }
}